package com.demo1031.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/demo1031/upload01.do")
public class FileUpload01Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先判断上传的数据是否是多段表单数据(只有多段表单数据，才是文件上传的)
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建 FileItemFactory 工厂类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传数据，得到每一个表单项
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //对每一个表单项进行循环判断，是普通类型还是上传的文件
                for (FileItem fileItem :
                        list) {
                    if (fileItem.isFormField()) {
                        //是普通表单项
                        System.out.println("表单项name属性：" + fileItem.getFieldName());
                        System.out.println("表单项value属性：" + fileItem.getString("UTF-8"));
                    } else {
                        //上传的文件
                        System.out.println("表单项name属性：" + fileItem.getFieldName());
                        System.out.println("上传的文件名" + fileItem.getName());
                        //将上传的文件保存到服务器本地
                        fileItem.write(new File("D:\\upload\\" + fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
